import axios from "axios";
import type { AxiosInstance, AxiosResponse } from "axios";
import { BASE_URL, TIME_OUT } from "@/service/config";
import { ElMessage } from "element-plus";

// 创建axios对象
const requst: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: TIME_OUT
});

// 请求拦截器
requst.interceptors.request.use((config) => {
  let token = sessionStorage.getItem("token");
  if (token && config.headers) {
    config.headers.Authorization = `Auth ${token}`;
  }
  return config;
}, (error) => {
  ElMessage.error("请求配置错误:" + (error.message || "未知错误"));
  return Promise.reject(error);
});

requst.interceptors.response.use((response: AxiosResponse) => {
  console.log("响应状态码：", response.status);

  // 如果是 blob 响应，直接返回整个 response 对象
  if (response.config.responseType === 'blob') {
    return response;
  }

  // 对于 JSON 响应，按原来的逻辑处理
  let res = response.data;
  if (res?.code !== 200) {
    console.log("响应异常：" + res.msg);
    return Promise.reject(new Error("响应异常" + res.msg));
  } else {
    return res;
  }
}, (error) => {
  return Promise.reject(error);
});

export default requst;
